package com.jushu.storbox.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jushu.storbox.AllFileMoveActivity;
import com.jushu.storbox.FileBrowserAllFileActivity;
import com.jushu.storbox.FileBrowserDocumentActivity;
import com.jushu.storbox.FileBrowserPictureActivity;
import com.jushu.storbox.LoginActivity;
import com.jushu.storbox.R;
import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.ShareDriveMainFragmentActivity;
import com.jushu.storbox.TranslateActivity;
import com.jushu.storbox.actions.FileFolderAction;
import com.jushu.storbox.actions.LinkAction;
import com.jushu.storbox.adapter.MyFileListAdapter;
import com.jushu.storbox.adapter.UploadSelectTypeAdapter;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.ExceptionConstant;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileType;
import com.jushu.storbox.entities.FolderInfo;
import com.jushu.storbox.entities.UploadSelectItem;
import com.jushu.storbox.handler.ClientExceptionRelateHandler;
import com.jushu.storbox.service.ICloudDriveService;
import com.jushu.storbox.service.ServiceFactory;
import com.jushu.storbox.util.LinkAccessCodeUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.NameUtils;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.util.XMLHelper;
import com.jushu.storbox.view.dialog.ClouddriveDialog;
import com.jushu.storbox.view.dialog.DateTimePickerDialog;
import com.jushu.storbox.view.dialog.MyPopupWindow;
import com.jushu.storbox.view.pulltorefresh.MyScrollView;
import com.jushu.storbox.view.pulltorefresh.PullDownElasticImp;
import com.jushu.storbox.view.pulltorefresh.PullDownScrollView;
import com.jushu.storbox.view.pulltorefresh.PullDownScrollView.RefreshListener;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.model.request.FolderCreateRequest;
import com.huawei.sharedrive.sdk.android.modelV2.request.LinkCreateRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.LinkInfoV2;
import com.huawei.sharedrive.sdk.android.service.handler.AsyncTaskHandler;
import com.huawei.sharedrive.sdk.android.util.StringUtil;

/**
 * show all file cloud ui fragment
 * 
 */
public class AllFileFragment extends BaseFragment {

	private static final String TAG = "AllFileFragment";

	/** upload RelativeLayout */
	private RelativeLayout filelist_tittle_upload_re;

	/** file list item tittle RelativeLayout */
	private RelativeLayout filelist_tittle_more_top_re;

	/** 'menu'(as three point icon) base layout */
	private RelativeLayout window_menu_View;

	/** activity object */
	private Activity activity;

	/** view inflater instance */
	private View viewLayoutInflater;

	/** upload select type gridview (ui) */
	private GridView uploadSelectTypeGV;

	/** cloud drive service */
	private ICloudDriveService shareDriveService;

	// /** cloud drive fileinfo list */
	// private List<FileFolderInfo> allFileList;

	/** folder id in current file list(default:0---root folder) */
	private String itemIDString = "0";

	/** upload select type adapter */
	private UploadSelectTypeAdapter uploadSelectTypeAdapter;

	/** confirm move file&folder bt */
	private Button move_confirm;

	/** folder name of move list */
	private TextView list_folder_name_tv;

	/** back RelativeLayout of move list */
	private RelativeLayout move_top_re;

	/** back imageview of move list */
	private ImageView list_folder_name_img;

	/** cancel move file&folder bt */
	private Button move_cancel;

	/** move operation lv */
	private ListView move_listView;

	/** move base view */
	private View window_move;

	/** move popupwindow */
	private MyPopupWindow moveMyPopupWindow;

	/** file list back base layout */
	private LinearLayout filelist_title_back_ll;

	/** file list back iv */
	private ImageView allfile_back_mi;

	/** resource is not exist 404 */
	public final static int resourceIsNotExist = 4;

	/** Authen failed 401 */
	private final static int failedToAuthen = 5;

	/** resource is exist 409 */
	private final static int resourceIsExist = 6;

	/** server Error 500 */
	private final static int serverError = 7;

	/** user account is locked 403 */
	private final static int userIsLocked = 8;

	/** server link failed 901 */
	private final static int serverLinkError = 9;

	/** request error 400 */
	private final static int errorRequest = 11;

	/** send from folder */
	private final static int sendFromCreateFolder = 1001;

	/** send from delete */
	private final static int sendFromDelete = 1002;

	/** send from move */
	private final static int sendFromMove = 1003;

	/** send from download */
	public final static int sendFromDownload = 1004;

	/** send from Rename */
	private final static int sendFromRename = 1005;

	private final static int uplodadUpdate = 1007;

	/** send from GetResource */
	private final static int sendFromGetResource = 1008;

	private boolean isDraging = false;

	/** relativeLayout state */
	private RelativeLayout state_re;

	/** TextView state */
	private TextView state_te;

	/** allfileFregment textView */
	private TextView filelist_tittle_text;

	/** allfileFregment ImageView */
	private ImageView filelist_tittle_img;

	private PullDownScrollView allfile_refresh_root;

	private MyScrollView allfile_scrollview;

	private LinearLayout allfile_layout;

	/** loading linearlayout */
	private LinearLayout loading_ll;

	/** current folder name */
	private TextView current_folder_text;

	private ClouddriveDialog addFileDialog;

	private static final int MENU_DIALOG = 30;

	private RelativeLayout cloud_search_back_re;

	private PopupWindow window_upload;

	private List<FileFolderInfo> currentRsource;

	private ImageView emptyImg;

	private FileFolderAction fileFolderActions;

	private Handler activityHandler;

	/** test */
	private String request_id = "0";

	private FileFolderInfo allInfo;

	private String returnParent;

	private ClouddriveDialog newsDialog;

	private LinearLayout movenews_lin;

	private List<FileFolderInfo> news_List;

	private int fromDir = UiConstant.DIR_CODE_BASE;

	private final static int MOVESUCCESSCODE = 4;

	private final static int MOVEFAILCODE = 5;

	private final static int TRANSLATE_REQUEST_CODE = 6;

	private FileFolderInfo moveInfo;

	private FileFolderInfo moveParentInfo;

	private boolean canDoResume = false;

	private RelativeLayout search_re;

	private LinearLayout shadow_ll;

	public MyScrollView getMyScrollView() {
		return this.allfile_scrollview;
	}

	@Override
	public PullDownScrollView getPullDownScrollView() {
		return this.allfile_refresh_root;
	}

	public List<FileFolderInfo> getNews_List() {
		return news_List;
	}

	public void setNews_List(List<FileFolderInfo> news_List) {
		this.news_List = news_List;
	}

	/**
	 * onAttach
	 * 
	 * @param activity
	 *            Activity instance
	 */
	@Override
	public void onAttach(Activity activity) {
		LogUtil.i(TAG, "AllFileFragment onAttach.");
		super.onAttach(activity);
		this.activity = (ShareDriveMainFragmentActivity) activity;
		setBack(false);
		if (null == getObj()) {
			// System.exit(1);
			PublicTools.restartApp(activity);
		} else {
			Map<String, Object> mp = (Map<String, Object>) getObj();
			LogUtil.i(TAG, "map:" + mp);
			if (null != (Handler) mp.get("activityhandler")) {
				activityHandler = (Handler) mp.get("activityhandler");
			} else {
				PublicTools.restartApp(activity);

			}
			if (null != (ICloudDriveService) mp.get("service")) {
				shareDriveService = (ICloudDriveService) mp.get("service");
			} else {
				PublicTools.restartApp(activity);
			}
			if (null != mp.get("dir")) {
				fromDir = (Integer) mp.get("dir");
			}
			allInfo = (FileFolderInfo) mp.get("all_entity");
			if (null != allInfo) {
				request_id = allInfo.getId();
				returnParent = allInfo.getName();
			} else {
				returnParent = getString(R.string.my_cloud_drive);
			}
		}
	}

	/**
	 * onCreate in Fragment
	 * 
	 * @param savedInstanceState
	 *            Bundle
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		IntentFilter filter = new IntentFilter(Constant.REFRESH_APPSTORE_ACTION);
		activity.registerReceiver(showInnerFolder, filter);

		IntentFilter stateFilter = new IntentFilter(Constant.REFRESH_ALLFILESTATE_ACTION);
		activity.registerReceiver(stateReceiver, stateFilter);
		// bindService
		// Intent bindIntent = new Intent(activity, CloudDriveService.class);
		// activity.bindService(bindIntent, serviceConnection,
		// Context.BIND_AUTO_CREATE);
		super.onCreate(savedInstanceState);
		LogUtil.i(TAG, "AllFileFragment onCreate.");
	}

	/**
	 * onCreateView in Fragment as that activiLogUtil.ncreate, you can init
	 * something.
	 * 
	 * @param inflater
	 *            LayoutInflater
	 * @param container
	 *            ViewGroup
	 * @param savedInstanceState
	 *            Bundle
	 * @return View fragment view
	 */
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		LogUtil.i(TAG, "AllFileFragment onCreateView.");
		// set content view in fragment
		viewLayoutInflater = inflater.inflate(R.layout.allfile_fragment, null);
		// init find view by id
		initFindViewById();
		// init data
		initData();
		// init onclick listenser
		initListenser();
		// return fragment view
		return viewLayoutInflater;
	}

	public void refreshListFromServer() {
	}

	public void refreshFileListUI() {
		// allfile_scrollview.getAdptor().notifyDataSetChanged();
	}

	/**
	 * action all listenser event in fragment.
	 */
	private void initListenser() {
		search_re.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (!ShareDriveApplication.getInstance().isFastDoubleClick()) {
					if (!ShareDriveApplication.getInstance().isScrolling()) {

						Message msg = new Message();
						msg.what = UiConstant.SHOW_SEARCH_BAR;
						setDir(UiConstant.DIR_CODE_1);
						activityHandler.sendMessage(msg);
					}
				}
			}
		});
		/** pull down refresh */
		allfile_refresh_root.setRefreshListener(new RefreshListener() {
			@Override
			public void onRefresh(PullDownScrollView view) {
				// TODO Auto-generated method stub
				if (View.VISIBLE == movenews_lin.getVisibility()) {
					Message msg = new Message();
					msg.what = UiConstant.REFRESH_FILELIST_UI_VIEW;
					msg.obj = getNews_List();
					handler.sendMessageDelayed(msg, 800);
				} else {
					fileFolderActions.getAllFileListFromServer(ShareDriveApplication.getInstance().getWnerID(), itemIDString, shareDriveService, 1);
				}
				isDraging = true;
			}
		});
		loading_ll.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

			}
		});

		// popup upload window
		filelist_tittle_upload_re.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				LogUtil.d(TAG, "click upload that will popup upload window.");
				// upload base view
				View window_upload_base = activity.getLayoutInflater().inflate(R.layout.window_upload, null);
				RelativeLayout window_upload_rl = (RelativeLayout) window_upload_base.findViewById(R.id.window_upload_rl);
				uploadSelectTypeGV = (GridView) window_upload_base.findViewById(R.id.window_upload_gv);
				ArrayList<UploadSelectItem> ploadSelectItemList = XMLHelper.parseUploadItemXml(activity);
				uploadSelectTypeAdapter = new UploadSelectTypeAdapter(activity, ploadSelectItemList, uploadWindowHandler);
				uploadSelectTypeGV.setAdapter(uploadSelectTypeAdapter);
				window_upload = new PopupWindow(activity);
				window_upload.setBackgroundDrawable(new BitmapDrawable());
				window_upload.setWidth(LayoutParams.MATCH_PARENT);
				window_upload.setHeight(LayoutParams.MATCH_PARENT);
				window_upload.setOutsideTouchable(true);
				window_upload.setFocusable(true);
				window_upload.setContentView(window_upload_base);
				window_upload.showAsDropDown(v);

				window_upload_rl.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {

						if (null != window_upload) {
							window_upload.dismiss();
						}
					}
				});
			}
		});
		// file list property function popup window
		filelist_tittle_more_top_re.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				handler.sendEmptyMessage(MENU_DIALOG);
			}
		});

		// move action confirm
		move_confirm.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (null != moveMyPopupWindow) {
					moveMyPopupWindow.closePopupWindow();
				}
				if (View.GONE == loading_ll.getVisibility()) {
					loading_ll.setVisibility(View.VISIBLE);
				}

			}
		});

		// file list back action
		filelist_title_back_ll.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				if (ShareDriveApplication.getInstance().isScrolling()) {
				} else {
					filelist_title_back_ll.setClickable(false);
					if (!"0".equals(itemIDString)) {
						// click back folder id(parent id)
						FileFolderInfo folderInfo = null;
						try {
							folderInfo = DAOFactory.instance(activity).getFolderDao()
									.getFolderById(ShareDriveApplication.getInstance().getWnerID(), itemIDString);
						} catch (Exception e) {
							// TODO: handle exception
							LogUtil.e(TAG, "file list back action exception:" + e.toString());
							e.printStackTrace();
						}
						if (null != folderInfo) {
							String parentFolder = folderInfo.getParent();
							if (null != parentFolder) {
								Bundle bundle = new Bundle();
								bundle.putString("folderID", parentFolder);
								bundle.putBoolean("return", true);
								Message msg = new Message();
								msg.setData(bundle);
								msg.what = UiConstant.GET_FILE_FOLDER_LIST;
								handler.sendMessage(msg);
							}
						} else {
							Bundle bundle = new Bundle();
							itemIDString = "0";
							bundle.putString("folderID", itemIDString);
							bundle.putBoolean("return", true);
							Message msg = new Message();
							msg.setData(bundle);
							msg.what = UiConstant.GET_FILE_FOLDER_LIST;
							handler.sendMessage(msg);
						}
					} else {
						itemIDString = "0";
						Bundle bundle = new Bundle();
						bundle.putString("folderID", itemIDString);
						bundle.putBoolean("return", true);
						Message msg = new Message();
						msg.setData(bundle);
						msg.what = UiConstant.GET_FILE_FOLDER_LIST;
						handler.sendMessage(msg);
					}
				}

			}
		});

		// move action cancel
		move_cancel.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {

				if (null != moveMyPopupWindow) {
					moveMyPopupWindow.closePopupWindow();
				}
			}
		});

	}

	/**
	 * init all data in fragment.
	 */
	private void initData() {

		allfile_refresh_root.setPullDownElastic(new PullDownElasticImp(activity));
		allfile_refresh_root.setRestSpeed(PullDownScrollView.RESETFAST);
		allfile_scrollview.setLayout(allfile_layout);

		filelist_tittle_text.setText(activity.getString(R.string.my_cloud_drive));
		filelist_tittle_text.setMaxEms(6);
		current_folder_text.setMaxEms(6);

		// init 9 gridview
		list_folder_name_img.setVisibility(View.GONE);
		fileFolderActions = new FileFolderAction(activity);
		fileFolderActions.setSuccessHandler(handler);
		fileFolderActions.setExceptionHandler(exceptionHandlers);
		if (UiConstant.DIR_CODE_1001 == fromDir) {
		} else {
			Message msg = new Message();
			Bundle bundler = new Bundle();
			bundler.putString("folderID", request_id);
			msg.setData(bundler);
			msg.what = UiConstant.GET_FILE_FOLDER_LIST;
			handler.sendMessage(msg);
		}
	}

	/**
	 * init all control find view by id in fragment.s
	 */
	private void initFindViewById() {

		allfile_refresh_root = (PullDownScrollView) viewLayoutInflater.findViewById(R.id.allfile_refresh_root);

		allfile_scrollview = (MyScrollView) viewLayoutInflater.findViewById(R.id.allfile_scrollview);

		allfile_layout = (LinearLayout) viewLayoutInflater.findViewById(R.id.allfile_layout);

		cloud_search_back_re = (RelativeLayout) viewLayoutInflater.findViewById(R.id.cloud_search_back_re);
		// file list back base layout
		filelist_title_back_ll = (LinearLayout) viewLayoutInflater.findViewById(R.id.filelist_title_back_ll);
		// filelist tittle textlayout
		filelist_tittle_text = (TextView) viewLayoutInflater.findViewById(R.id.filelist_tittle_text);
		// file list back iv
		allfile_back_mi = (ImageView) viewLayoutInflater.findViewById(R.id.allfile_back_mi);
		// upload iv
		filelist_tittle_upload_re = (RelativeLayout) viewLayoutInflater.findViewById(R.id.filelist_tittle_upload_re);

		// file list item tittle iv
		filelist_tittle_more_top_re = (RelativeLayout) viewLayoutInflater.findViewById(R.id.filelist_tittle_more_top_re);
		// 'menu'(as three point icon) base layout
		window_menu_View = (RelativeLayout) viewLayoutInflater.findViewById(R.id.filelist_tittle_re);

		// get layout inflater
		LayoutInflater moveInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		// move base view
		window_move = moveInflater.inflate(R.layout.window_move, null);
		// move confirm bt
		move_confirm = (Button) window_move.findViewById(R.id.confirm_btn);
		// move cancel bt
		move_cancel = (Button) window_move.findViewById(R.id.canccle_btn);
		// move listView lv
		move_listView = (ListView) window_move.findViewById(R.id.FileList_lv);
		// move back img
		list_folder_name_img = (ImageView) window_move.findViewById(R.id.list_folder_name_img);
		// move back RelativeLayout
		move_top_re = (RelativeLayout) window_move.findViewById(R.id.share_file_folder_list_top_re);
		// move current folder
		list_folder_name_tv = (TextView) window_move.findViewById(R.id.list_folder_name_tv);

		state_re = (RelativeLayout) viewLayoutInflater.findViewById(R.id.state_re);

		state_te = (TextView) viewLayoutInflater.findViewById(R.id.state_te);

		filelist_tittle_img = (ImageView) viewLayoutInflater.findViewById(R.id.filelist_tittle_img);

		loading_ll = (LinearLayout) viewLayoutInflater.findViewById(R.id.loading_ll);

		current_folder_text = (TextView) viewLayoutInflater.findViewById(R.id.current_folder_text);
		movenews_lin = (LinearLayout) viewLayoutInflater.findViewById(R.id.movenews_lin);
		search_re = (RelativeLayout) viewLayoutInflater.findViewById(R.id.search_re);
		shadow_ll = (LinearLayout) viewLayoutInflater.findViewById(R.id.shadow_ll);
	}

	/**
	 * onActivityCreated in Fragment
	 * 
	 * @param savedInstanceState
	 *            Bundle
	 */
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		LogUtil.i(TAG, "AllFileFragment onActivityCreated");
		super.onActivityCreated(savedInstanceState);
	}

	/**
	 * onStart in Fragment
	 */
	@Override
	public void onStart() {
		LogUtil.i(TAG, "AllFileFragment onStart");
		super.onStart();
	}

	/**
	 * onStart in Fragment
	 */
	@Override
	public void onResume() {
		LogUtil.i(TAG, "AllFileFragment onResume");
		if (!ShareDriveApplication.getInstance().getWifiController().getNetworkState()) {
			if (View.GONE == state_re.getVisibility()) {
				state_re.setVisibility(View.VISIBLE);
			}
		} else {
			if (View.VISIBLE == state_re.getVisibility()) {
				state_re.setVisibility(View.GONE);
			}
		}
		if ("0".equals(itemIDString)) {
			if (canDoResume) {
				String folderIsChanged = DAOFactory.instance(activity).getFolderDao()
						.getChangedFolderId(ShareDriveApplication.getInstance().getWnerID(), itemIDString);
				LogUtil.i(TAG, "folderIsChanged:" + folderIsChanged);
				if (null != folderIsChanged && "1".equals(folderIsChanged)) {
					DAOFactory.instance(activity).getFolderDao().setChangedFolderId(ShareDriveApplication.getInstance().getWnerID(), itemIDString, "0");
					getAllFileList(itemIDString, 25);
				}
			}
			canDoResume = true;
		}
		super.onResume();
	}

	/**
	 * onStart in Fragment
	 */
	@Override
	public void onPause() {
		LogUtil.i(TAG, "AllFileFragment onPause");
		super.onPause();
	}

	/**
	 * onStart in Fragment
	 */
	@Override
	public void onStop() {
		LogUtil.i(TAG, "AllFileFragment onStop");
		super.onStop();
	}

	/**
	 * onStart in Fragment
	 */
	@Override
	public void onDestroy() {
		LogUtil.i(TAG, "AllFileFragment onDestroy");
		// dismiss popup window
		if (null != moveMyPopupWindow) {
			moveMyPopupWindow.closePopupWindow();
		}
		// unregister receiver
		activity.unregisterReceiver(showInnerFolder);
		activity.unregisterReceiver(stateReceiver);
		super.onDestroy();
	}

	/**
	 * onDestroyView in Fragment
	 */
	@Override
	public void onDestroyView() {
		LogUtil.i(TAG, "AllFileFragment onDestroyView");
		super.onDestroyView();
	}

	/**
	 * onDetach in Fragment
	 */
	@Override
	public void onDetach() {
		LogUtil.i(TAG, "AllFileFragment onDetach");
		super.onDetach();
	}

	/**
	 * about upload choose file callback
	 * 
	 * @param requestCode
	 *            int return request code
	 * @param resultCode
	 *            int return reulst code success or fail
	 * @param data
	 *            Intent return binder upload choose data
	 */
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case 1:
			if (resultCode == 2) {
				// Get the Uri of the selected file
				LogUtil.i(TAG, "Get the Uri of the selected file.");
				Bundle bundle = data.getBundleExtra("result");
				List<String> resultUrlList = bundle.getStringArrayList("resultUIL");
				// Get the path
				fileFolderActions.uploadFileOrinitLogin(shareDriveService, resultUrlList);
			}
			break;
		case 2:
			if (resultCode == 3) {
				// refresh after clear
				Message refurbishMsg = new Message();
				Bundle uploadBundle = new Bundle();
				uploadBundle.putString("folderID", itemIDString);
				refurbishMsg.setData(uploadBundle);
				refurbishMsg.what = UiConstant.GET_FILE_FOLDER_LIST;
				handler.sendMessage(refurbishMsg);
			}
			break;
		}
		switch (resultCode) {
		case MOVESUCCESSCODE:
			if (View.GONE == loading_ll.getVisibility()) {
				loading_ll.setVisibility(View.VISIBLE);
			}
			setBack(false);
			Log.d("moverespnse", "MOVESUCCESSCODE");
			Bundle allFileMoveConfirmBundle = data.getBundleExtra("moverespnse");
			moveParentInfo = (FileFolderInfo) allFileMoveConfirmBundle.getSerializable("parentInfo");
			moveConfirm();
			break;
		case MOVEFAILCODE:
			Log.d("moverespnse", "MOVEFAILCODE");
			moveCancle();
			break;

		case TRANSLATE_REQUEST_CODE:
			break;

		default:
			break;
		}

		super.onActivityResult(requestCode, resultCode, data);

	}

	/**
	 * get file&folder list from cloud server that refresh ui
	 * 
	 * @param onReceive
	 *            broadcat callback
	 * @return refresh ui broadcast
	 */
	private BroadcastReceiver showInnerFolder = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			itemIDString = intent.getStringExtra("fId");
			int isShowDailog = intent.getIntExtra("isShowDailog", 0);
			Message uploadMsg = new Message();
			Bundle uploadBundle = new Bundle();
			uploadBundle.putString("folderID", itemIDString);
			uploadMsg.setData(uploadBundle);
			uploadMsg.what = UiConstant.GET_FILE_FOLDER_LIST;
			uploadMsg.arg1 = isShowDailog;
			handler.sendMessage(uploadMsg);
		}
	};

	/**
	 * get file&folder list from cloud server that refresh ui
	 * 
	 * @param onReceive
	 *            broadcat callback
	 * @return refresh ui broadcast
	 */
	private Handler handler = new Handler() {
		@SuppressLint("ResourceAsColor")
		public void handleMessage(android.os.Message msg) {
			LogUtil.i(TAG, "handler get file&folder list from cloud server that refresh ui messgae what:" + msg.what);
			switch (msg.what) {
			case UiConstant.HIDE_LODING_PROGREESS:
				if (View.VISIBLE == loading_ll.getVisibility()) {
					loading_ll.setVisibility(View.GONE);
				}
				break;

			case UiConstant.DISPLAY_FILELIST_UI_VIEW:
				List<FileFolderInfo> search_fll = (ArrayList<FileFolderInfo>) msg.obj;
				showMsgData(search_fll);
				break;
			case UiConstant.SEARCH_FILE_BY_NAME:
				search("");
				break;
			case UiConstant.OPEN_FOLDER_BY_FILEFOLDERINFO:
				Message ac_msg = new Message();
				ac_msg.what = UiConstant.ALLFILEFRAGMENT;
				ac_msg.obj = msg.obj;
				ac_msg.arg1 = 25;
				activityHandler.sendMessage(ac_msg);
				break;
			// refresh file&folder list view
			case 0:
				ShareDriveApplication.getInstance().setMyCloudDrivePage(0);
				Bundle listBundler = msg.getData();
				String folderID = listBundler.getString("folderID");
				if (null != folderID) {
					itemIDString = folderID;
				}
				boolean flag = true;
				if (!listBundler.getBoolean("return")) {
					flag = false;
				}
				break;
			case UiConstant.REFRESH_FILELIST_UI_VIEW:
				// refresh page
				List<FileFolderInfo> ffl = (ArrayList<FileFolderInfo>) msg.obj;
				showMsgData(ffl);
				onDataLoaded();
				break;

			case UiConstant.SUCCESS_GET_SERVER_FOLDER_INFOMATION:
				Message uiHandler = activityHandler.obtainMessage();
				uiHandler.what = UiConstant.SUCCESS_GET_SERVER_FOLDER_INFOMATION;
				uiHandler.obj = msg.obj;
				uiHandler.sendToTarget();
				break;

			case UiConstant.SUCCESS_ON_FILE_FOLDER_INFO_CHANGED:
				// add view into page
				if (null != emptyImg) {
					if (null != allfile_layout && null != allfile_layout.getChildAt(0)) {
						allfile_layout.removeView(emptyImg);
						emptyImg = null;
					}
				}
				if (sendFromDelete == msg.arg1) {
					View item = (View) msg.obj;
					if (null != item) {
						currentRsource.remove(item);
						BaseAdapter mAdapter = new MyFileListAdapter(activity, handler, currentRsource, shareDriveService);
						allfile_scrollview.setAdptor(mAdapter);
						allfile_scrollview.removeItem(item);
					}
				} else if (sendFromCreateFolder == msg.arg1) {
					FileFolderInfo entity = (FileFolderInfo) msg.obj;
					if (null != entity) {
						currentRsource.add(0, entity);
						BaseAdapter mAdapter = new MyFileListAdapter(activity, handler, currentRsource, shareDriveService);
						allfile_scrollview.setAdptor(mAdapter);
						allfile_scrollview.addOneItemAt(0, mAdapter.getView(0, null, null));
					} else {
						Toast.makeText(activity, getString(R.string.allfile_have_no_more_filefolder), Toast.LENGTH_SHORT).show();
					}
				} else if (sendFromRename == msg.arg1) {
					Bundle bundle = msg.getData();
					FileFolderInfo entity = (FileFolderInfo) bundle.getSerializable("entity");
					// String filePath = bundle.getString("filePath");
					View item = (View) msg.obj;
					if (null != item && null != entity) {
						allfile_scrollview.notifyitem(item, entity);
					}
				} else if (uplodadUpdate == msg.arg1) {

					FileFolderInfo fileInformation = (FileFolderInfo) msg.obj;

					boolean haveNewItemAdded = true;
					for (FileFolderInfo fileFolderInfo : currentRsource) {
						if (fileInformation.getId().equals(fileFolderInfo.getId())) {
							haveNewItemAdded = false;
							break;
						}
					}
					if (haveNewItemAdded) {
						currentRsource.add(0, fileInformation);
					}
					BaseAdapter mAdapter = new MyFileListAdapter(activity, handler, currentRsource, shareDriveService);
					allfile_scrollview.setAdptor(mAdapter);
					if (haveNewItemAdded) {
						allfile_scrollview.addOneItemAt(0, mAdapter.getView(0, null, null));
					}
				}
				if (View.VISIBLE == loading_ll.getVisibility()) {
					loading_ll.setVisibility(View.GONE);
				}
				break;
			case resourceIsNotExist:// 404
				Toast.makeText(activity, getString(R.string.allfile_filefolder_no_exist), Toast.LENGTH_SHORT).show();
				if (sendFromDelete == msg.arg1 || sendFromMove == msg.arg1 || sendFromRename == msg.arg1 || sendFromDownload == msg.arg1) {
					View viewItem = (View) msg.obj;
					if (null != viewItem) {
						MyFileListAdapter.ViewHolder viewHolder = (MyFileListAdapter.ViewHolder) viewItem.getTag();
						((MyFileListAdapter) allfile_scrollview.getAdptor()).fileList.remove(viewHolder.fileInformation);
						ServiceFactory.instance(activity).getLocalFileService().deleteFile(viewHolder.fileInformation);
						allfile_scrollview.removeItem(viewItem);
						// currentRsource.remove(item);
						// BaseAdapter mAdapter = new
						// MyFileListAdapter(activity, handler, currentRsource,
						// shareDriveService);
						// allfile_scrollview.setAdptor(mAdapter);
						// allfile_scrollview.notifyitem(item, entity);
					}
				}
				if (View.VISIBLE == loading_ll.getVisibility()) {
					loading_ll.setVisibility(View.GONE);
				}
				break;
			case failedToAuthen:// 401
				// if (2001 == msg.arg1) {
				// Message dataBaseMsg = new Message();
				// dataBaseMsg.what = 1;
				// handler.sendMessage(dataBaseMsg);
				// }
				new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (null != shareDriveService) {
							shareDriveService.loginIn(PublicTools.getLoginUserName(activity), PublicTools.getLoginUserPassFail(activity), null);
						}
					}
				}).start();
				break;
			case resourceIsExist:// 409
				// handle createFolder
				if (sendFromCreateFolder == msg.arg1) {
					AlertDialog.Builder aDialog = new AlertDialog.Builder(activity);
					aDialog.setTitle(activity.getString(R.string.rename_dialog_title));
					aDialog.setMessage(activity.getString(R.string.rename_folder_dialog_message));
					aDialog.setNegativeButton(activity.getString(R.string.button_no), new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							arg0.cancel();
						}
					});
					aDialog.setPositiveButton(activity.getString(R.string.button_yes), new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							createFolder();

						}
					});
					aDialog.show();
				}
				if (sendFromMove == msg.arg1) {
					Toast.makeText(activity, activity.getString(R.string.allfile_file_exists_name), Toast.LENGTH_SHORT).show();
				}
				if (sendFromRename == msg.arg1) {
					// rename folder exist then you need rename again
					final View renameItems = (View) msg.obj;
					Bundle renameBundle_exist = msg.getData();
					final FileFolderInfo renameInfo_exist = (FileFolderInfo) renameBundle_exist.getSerializable("folderID");
					AlertDialog.Builder renameDialog = new AlertDialog.Builder(activity);
					renameDialog.setTitle(activity.getString(R.string.rename_dialog_title));
					if (renameInfo_exist.getIsFile() == 1) {
						renameDialog.setMessage(activity.getString(R.string.rename_file_dialog_message));
					} else {
						renameDialog.setMessage(activity.getString(R.string.rename_folder_dialog_message));
					}
					renameDialog.setNegativeButton(activity.getString(R.string.button_no), new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface arg0, int arg1) {

							arg0.cancel();
						}
					});
					renameDialog.setPositiveButton(activity.getString(R.string.button_yes), new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface arg0, int arg1) {

							rename(activity, renameInfo_exist, renameItems);
						}
					});
					renameDialog.show();
				}
				break;
			case serverError:// 500
				break;
			case userIsLocked:// 403
				Toast.makeText(activity, activity.getString(R.string.allfile_account_is_locked), Toast.LENGTH_SHORT).show();
				break;
			case serverLinkError:// 901
				// if (View.VISIBLE == loading_ll.getVisibility()) {
				// loading_ll.setVisibility(View.GONE);
				// }
				// if (!filelist_title_back_ll.isClickable()) {
				// filelist_title_back_ll.setClickable(true);
				// }
				Toast.makeText(activity, activity.getString(R.string.allfile_network_inavailable), Toast.LENGTH_SHORT).show();
				break;
			case UiConstant.GET_FILE_FOLDER_LIST:
				if (View.GONE == loading_ll.getVisibility()) {
					loading_ll.setVisibility(View.VISIBLE);
				}
				if (filelist_title_back_ll.isClickable()) {
					filelist_title_back_ll.setClickable(false);
				}
				boolean isAuto = true;
				Bundle pullBundler = msg.getData();
				String pullFolderID = pullBundler.getString("folderID");
				long currentTimeMills = System.currentTimeMillis();
				long dbTimeMills = DAOFactory.instance(activity).getFolderDao()
						.getLastRefreshTime(ShareDriveApplication.getInstance().getWnerID(), pullFolderID);
				/* display data of database * */
				if (0 != dbTimeMills) {
					getAllFileList(pullFolderID, 1);
				}
				String time = PublicTools.longToString(dbTimeMills);
				allfile_refresh_root.setLastUpdateTime(time);
				if ((currentTimeMills - dbTimeMills > ClientConfig.REFRESH_TIME || dbTimeMills == 0l) && isAuto) {
					int dir = UiConstant.DIR_CODE_25;
					if (UiConstant.DIR_CODE_1 == fromDir) {
						dir = UiConstant.DIR_CODE_1;
					}
					if (0 == dbTimeMills) {
						dir = UiConstant.DIR_CODE_1;
					}
					fileFolderActions.getAllFileListFromServer(ShareDriveApplication.getInstance().getWnerID(), pullFolderID, shareDriveService, dir);
				}
				if (null != pullFolderID) {
					itemIDString = pullFolderID;
				}
				changeFolderInfor();
				break;
			case errorRequest:
				// if (2001 == msg.arg1) {
				// Message dataBaseMsg = new Message();
				// dataBaseMsg.what = 1;
				// handler.sendMessage(dataBaseMsg);
				// }
				new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (null != shareDriveService) {
							shareDriveService.loginIn(PublicTools.getLoginUserName(activity), PublicTools.getLoginUserPassFail(activity), null);
						}
					}
				}).start();
				break;
			case UiConstant.MOVE_FILE_FOLDER_ITEM:
				moveInfo = (FileFolderInfo) msg.obj;
				startMoveActivity(moveInfo);
				break;
			case UiConstant.SUCCESS_ON_FILE_FOLDER_REMOVE:
				getAllFileList(itemIDString, 1);
				Message amcMsg = new Message();
				amcMsg.what = UiConstant.ALLFILEFRAGMENT;
				amcMsg.arg1 = 25;
				amcMsg.obj = moveParentInfo;
				moveParentInfo = null;
				activityHandler.sendMessageDelayed(amcMsg, 500);
				break;
			case 14:
				// getAllFileList(itemIDString);
				break;
			case UiConstant.RENAME_FILEFOLDER_ITEM:
				// rename file&folder operate
				Bundle renameBundle = msg.getData();
				View renameitem = (View) msg.obj;
				FileFolderInfo renameInfo = (FileFolderInfo) renameBundle.getSerializable("rename");
				rename(activity, renameInfo, renameitem);
				break;
			case UiConstant.DELETE_FILEFOLDER_ITEM:
				Bundle deleteBundle = msg.getData();
				final View deleteitem = (View) msg.obj;
				final FileFolderInfo deleteInfo = (FileFolderInfo) deleteBundle.getSerializable("delete");
				final ClouddriveDialog delete = new ClouddriveDialog(activity, R.style.dialog_upload, R.layout.dialog_filedelete);

				View conventView = delete.getConventView();
				Button dialog_cancal = (Button) conventView.findViewById(R.id.dialog_add_file_cancal_bt);

				Button dialog_OK = (Button) conventView.findViewById(R.id.dialog_add_file_ok_bt);

				TextView dialog_prompt_tv = (TextView) conventView.findViewById(R.id.dialog_prompt_tv);
				dialog_prompt_tv.setText(activity.getString(R.string.allfile_confirm_delete_filefolder));

				dialog_cancal.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						delete.dismiss();
					}
				});

				dialog_OK.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						delete.dismiss();
						delete(activity, deleteInfo, deleteitem);
					}
				});
				delete.show();
				break;

			case UiConstant.ERROR_OCURRED_CONNECT_SERVER:// login return code
															// 901, connect
															// server fail
				AlertDialog.Builder serverErrer = new AlertDialog.Builder(activity);
				serverErrer.setTitle(activity.getString(R.string.rename_dialog_title));
				serverErrer.setMessage(activity.getString(R.string.allfile_failed_serve_connection_failed));
				serverErrer.setNegativeButton(activity.getString(R.string.button_cancel), new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						arg0.cancel();
					}
				});
				serverErrer.setPositiveButton(activity.getString(R.string.button_ok), new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						Intent intent = new Intent();
						intent.setClass(activity, LoginActivity.class);
						startActivity(intent);
					}
				});
				serverErrer.show();
				break;
			case UiConstant.NETWORK_OBSTRUCTED:
				// network disable
				Toast.makeText(activity, activity.getString(R.string.allfile_notwork_obstructed), 200).show();
				break;

			case 22:// move exception handle
				Toast.makeText(activity, activity.getString(R.string.allfile_notwork_exist), Toast.LENGTH_SHORT).show();
				break;
			case UiConstant.FOLDER_NAME_IS_INVALID:
				// Toast.makeText(activity,
				// activity.getString(R.string.allfile_file_not_standard), 200)
				// .show();
				if (View.VISIBLE == loading_ll.getVisibility()) {
					loading_ll.setVisibility(View.GONE);
				}
				break;
			/** more update notify */
			case UiConstant.DIR_CODE_25:
				int dir = msg.arg1;
				if (shareDriveService.getResourceIsChange() || UiConstant.DIR_CODE_200 == dir) {
					getNewsView();
					setNews_List((List<FileFolderInfo>) msg.obj);
				}
				break;
			/** set link */
			case UiConstant.SET_SHARE_LINK:
				Bundle linkBundle = msg.getData();
				View linkitem = (View) msg.obj;
				FileFolderInfo fileFolderInfo = (FileFolderInfo) linkBundle.getSerializable("link");
				setLinkInfo(activity, fileFolderInfo, linkitem);
				break;
			/** open link share ui */
			case UiConstant.POPUP_SHARE_LINK_UI:
				Bundle lBundle = msg.getData();
				View litem = (View) msg.obj;
				FileFolderInfo fInfo = (FileFolderInfo) lBundle.getSerializable("FileFolderInfo");
				LinkInfoV2 info = (LinkInfoV2) lBundle.getSerializable("LinkInfo");
				Boolean isComplexAccessCode = (Boolean) lBundle.getSerializable("LinkConfigInfo");
				shareLinkInfo(activity, fInfo, info, litem, isComplexAccessCode);
				break;
			case 409:
				Toast.makeText(activity, activity.getString(R.string.allfile_file_exists_name), Toast.LENGTH_LONG).show();
				break;
			case MENU_DIALOG:// menu dialog
				initMenuDialog();
				break;

			case ClientConfig.SENDFROMSHARELINK:
				handler.sendEmptyMessage(UiConstant.HIDE_LODING_PROGREESS);
				HashMap<String, Object> linklMap = (HashMap<String, Object>) msg.obj;
				LinkInfoV2 infol = (LinkInfoV2) linklMap.get("LinkInfo");
				View view = (View) linklMap.get("view");
				MyFileListAdapter.ViewHolder viewHolder = (MyFileListAdapter.ViewHolder) view.getTag();
				sendFileLinkPerson(infol, viewHolder.fileInformation);
				break;

			case ClientConfig.SENDFROMUPLOADFILE:
				if (null != shareDriveService) {
					shareDriveService.uploadFile(request_id, (List<String>) msg.obj, null, handler);
				}
				break;

			default:
				break;
			}
		};
	};

	public void initNewsDialog(final List<FileFolderInfo> resource, ClouddriveDialog newsDialog) {
		if (null == newsDialog) {
			newsDialog = new ClouddriveDialog(activity, R.style.dialog_menu_theme, R.layout.window_news);
			newsDialog.setHeigth(LayoutParams.WRAP_CONTENT);
			newsDialog.setWidth(LayoutParams.MATCH_PARENT);
			newsDialog.setCancelable(false);
			newsDialog.setCanceledOnTouchOutside(true);
			newsDialog.show();
			newsDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

				@Override
				public void onDismiss(DialogInterface arg0) {
					// TODO Auto-generated method stub
					Message msg = new Message();
					msg.what = UiConstant.REFRESH_FILELIST_UI_VIEW;
					msg.obj = resource;
					handler.sendMessage(msg);
				}
			});
		}
	}

	public void initMenuDialog() {
		final ClouddriveDialog menuDialog = new ClouddriveDialog(activity, R.style.dialog_menu_theme, R.layout.dialog_menu);
		menuDialog.setHeigth(LayoutParams.WRAP_CONTENT);
		menuDialog.setWidth(LayoutParams.MATCH_PARENT);
		menuDialog.setCanceledOnTouchOutside(true);
		menuDialog.show();
		View conventView = menuDialog.getConventView();

		// RelativeLayout window_menu_setting_ll = (RelativeLayout) conventView
		// .findViewById(R.id.window_menu_setting_ll);

		RelativeLayout addFile = (RelativeLayout) conventView.findViewById(R.id.add_lin);

		RelativeLayout addFolder = (RelativeLayout) conventView.findViewById(R.id.add_folder_lin);

		RelativeLayout rangeByTime = (RelativeLayout) conventView.findViewById(R.id.range_time_lin);

		RelativeLayout rangeBySize = (RelativeLayout) conventView.findViewById(R.id.range_size_lin);

		RelativeLayout rangeByName = (RelativeLayout) conventView.findViewById(R.id.range_name_lin);

		RelativeLayout translateList = (RelativeLayout) conventView.findViewById(R.id.translate_list_lin);

		final ImageView rangeByTime_Img = (ImageView) conventView.findViewById(R.id.range_time_img);

		final ImageView rangeBySize_Img = (ImageView) conventView.findViewById(R.id.range_size_img);

		final ImageView rangeByName_Img = (ImageView) conventView.findViewById(R.id.range_name_img);

		LinearLayout linearLayout = (LinearLayout) conventView.findViewById(R.id.meun_bg_loaves_ll);
		String orderBy = PublicTools.getOrderBy(activity);
		String des = PublicTools.getDes(activity);

		rangeBySize_Img.setVisibility(View.INVISIBLE);
		rangeByName_Img.setVisibility(View.INVISIBLE);
		rangeByTime_Img.setVisibility(View.INVISIBLE);
		if ("name".equals(orderBy)) {
			rangeByName_Img.setVisibility(View.VISIBLE);
			if ("DESC".equals(des)) {
				rangeByName_Img.setImageResource(R.mipmap.order_down);
			} else {
				rangeByName_Img.setImageResource(R.mipmap.order_up);
			}
		} else if ("size".equals(orderBy)) {
			rangeBySize_Img.setVisibility(View.VISIBLE);
			if ("DESC".equals(des)) {
				rangeBySize_Img.setImageResource(R.mipmap.order_down);
			} else {
				rangeBySize_Img.setImageResource(R.mipmap.order_up);
			}
		} else {
			rangeByTime_Img.setVisibility(View.VISIBLE);
			if ("DESC".equals(des)) {
				rangeByTime_Img.setImageResource(R.mipmap.order_down);
			} else {
				rangeByTime_Img.setImageResource(R.mipmap.order_up);
			}
		}

		addFile.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				menuDialog.dismiss();
				addFileDialog = new ClouddriveDialog(activity, R.style.dialog_upload, R.layout.dialog_addfile);
				addFileDialog.setPosition(0, Gravity.BOTTOM);
				WindowManager windowManager = activity.getWindowManager();
				Display display = windowManager.getDefaultDisplay();
				addFileDialog.setWidth(display.getWidth());
				addFileDialog.show();
				dialogAddfileClick();
			}
		});
		addFolder.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				menuDialog.dismiss();
				createFolder();
			}
		});
		// click rangeByTime that will refresh all cloud list data
		rangeByTime.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				menuDialog.dismiss();
				ShareDriveApplication.getInstance().setMyCloudDrivePage(0);
				String des = PublicTools.getDes(activity);
				if (!"DESC".equals(des)) {
					PublicTools.setDes(activity, "DESC");
				} else {
					PublicTools.setDes(activity, "ASC");
				}
				PublicTools.setOrderBy(activity, "modifiedAt");
				Message msg = new Message();
				Bundle bundle = new Bundle();
				bundle.putString("folderID", itemIDString);
				bundle.putBoolean("isAuto", false);
				msg.setData(bundle);
				msg.what = UiConstant.GET_FILE_FOLDER_LIST;
				handler.sendMessage(msg);
				des = PublicTools.getDes(activity);
				if ("DESC".equals(des)) {
					rangeByTime_Img.setImageResource(R.mipmap.order_down);
				} else {
					rangeByTime_Img.setImageResource(R.mipmap.order_up);
				}
				rangeByTime_Img.setVisibility(View.VISIBLE);
			}
		});

		rangeBySize.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				menuDialog.dismiss();
				ShareDriveApplication.getInstance().setMyCloudDrivePage(0);
				String des = PublicTools.getDes(activity);
				if (!"DESC".equals(des)) {
					PublicTools.setDes(activity, "DESC");
				} else {
					PublicTools.setDes(activity, "ASC");
				}
				PublicTools.setOrderBy(activity, "size");
				Message msg = new Message();
				Bundle bundle = new Bundle();
				bundle.putString("folderID", itemIDString);
				bundle.putBoolean("isAuto", false);
				msg.setData(bundle);
				msg.what = UiConstant.GET_FILE_FOLDER_LIST;
				handler.sendMessage(msg);
				des = PublicTools.getDes(activity);
				if ("DESC".equals(des)) {
					rangeBySize_Img.setImageResource(R.mipmap.order_down);
				} else {
					rangeBySize_Img.setImageResource(R.mipmap.order_up);
				}
				rangeBySize_Img.setVisibility(View.VISIBLE);
			}
		});

		rangeByName.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				menuDialog.dismiss();
				ShareDriveApplication.getInstance().setMyCloudDrivePage(0);
				String des = PublicTools.getDes(activity);
				if (!"DESC".equals(des)) {
					PublicTools.setDes(activity, "DESC");
				} else {
					PublicTools.setDes(activity, "ASC");
				}
				PublicTools.setOrderBy(activity, "name");
				Message msg = new Message();
				Bundle bundle = new Bundle();
				bundle.putString("folderID", itemIDString);
				bundle.putBoolean("isAuto", false);
				msg.setData(bundle);
				msg.what = UiConstant.GET_FILE_FOLDER_LIST;
				handler.sendMessage(msg);
				des = PublicTools.getDes(activity);
				if ("DESC".equals(des)) {
					rangeByName_Img.setImageResource(R.mipmap.order_down);
				} else {
					rangeByName_Img.setImageResource(R.mipmap.order_up);
				}
				rangeByName_Img.setVisibility(View.VISIBLE);
			}
		});

		linearLayout.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				menuDialog.dismiss();
			}
		});

		translateList.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent translateActvity = new Intent();
				translateActvity.setClass(activity, TranslateActivity.class);
				startActivityForResult(translateActvity, TRANSLATE_REQUEST_CODE);
				menuDialog.dismiss();
			}

		});
	}

	/**
	 * upload file choose which file type to open file dialog browser
	 */
	private Handler uploadWindowHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (null != addFileDialog) {
				addFileDialog.dismiss();
			}
			switch (msg.what) {
			case 0:
				// create folder
				createFolder();
				if (null != window_upload) {
					window_upload.dismiss();
				}
				break;
			case 1:
				// picture
				Intent dataPicture = new Intent();
				dataPicture.setClass(activity, FileBrowserPictureActivity.class);
				startActivityForResult(dataPicture, 1);
				if (null != window_upload) {
					window_upload.dismiss();
				}
				break;
			case 2:
				// document
				Intent dataDocument = new Intent();
				dataDocument.setClass(activity, FileBrowserDocumentActivity.class);
				startActivityForResult(dataDocument, 1);
				if (null != window_upload) {
					window_upload.dismiss();
				}
				break;
			case 3:
				// all
				// showFileChooser(4);
				Intent dataAllFile = new Intent();
				dataAllFile.setClass(activity, FileBrowserAllFileActivity.class);
				// dataAllFile.putExtra("type", "all");
				startActivityForResult(dataAllFile, 1);
				if (null != window_upload) {
					window_upload.dismiss();
				}
				break;
			default:
				break;
			}
		}
	};

	/**
	 * create folder
	 */
	public void createFolder() {
		final ClouddriveDialog createFolder = new ClouddriveDialog(activity, R.style.dialog_upload, R.layout.window_dialog_create_folder);
		View conventView = createFolder.getConventView();
		Button confirm_btn = (Button) conventView.findViewById(R.id.confirm_btn);
		Button cancle_btn = (Button) conventView.findViewById(R.id.cancle_btn);
		TextView tittleText = (TextView) conventView.findViewById(R.id.tittle_tv);
		final EditText input_et = (EditText) conventView.findViewById(R.id.inputText_et);
		tittleText.setText(activity.getString(R.string.create_folder));

		cancle_btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				createFolder.dismiss();
				if (View.VISIBLE == loading_ll.getVisibility()) {
					loading_ll.setVisibility(View.GONE);
				}
			}
		});
		confirm_btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!ShareDriveApplication.getInstance().isFastDoubleClick()) {
					if (ShareDriveApplication.getInstance().getWifiController().getNetworkState()) {
						if (View.GONE == loading_ll.getVisibility()) {
							loading_ll.setVisibility(View.VISIBLE);
						}
					}
					createFolder.dismiss();
					if (!ShareDriveApplication.getInstance().getWifiController().getNetworkState()) {
						Toast.makeText(activity, activity.getString(R.string.allfile_search_is_not_vailible), Toast.LENGTH_SHORT).show();

					} else {
						if (!NameUtils.isValidFileName(input_et.getText().toString())) {
							Toast.makeText(activity, activity.getString(R.string.allfile_file_name_not_standard), Toast.LENGTH_SHORT).show();
							if (View.VISIBLE == loading_ll.getVisibility()) {
								loading_ll.setVisibility(View.GONE);
							}
							createFolder();
							return;
						} else {
							// TODO need modify
							final FolderCreateRequest request = new FolderCreateRequest();
							request.setName(input_et.getText().toString());
							request.setParent(request_id);
							new Thread(new Runnable() {
								public void run() {
									// Message msg = new Message();
									FileFolderInfo folder = null;
									// try {
									if (null != shareDriveService) {
										folder = fileFolderActions.createFolder(ShareDriveApplication.getInstance().getWnerID(), shareDriveService, request);
									}
								}

							}).start();
						}
					}
				}
			}
		});
		createFolder.show();
		PublicTools.showKey(input_et, activity);
	}

	/**
	 * rename file&folder
	 * 
	 * @param context
	 *            Context
	 * @param fileInformation
	 *            FileInformation cloud drive data
	 */
	private void rename(Context context, final FileFolderInfo fileInformation, final View item) {
		String name = fileInformation.getName();
		if (0 == fileInformation.getIsFile()) {// folder
			FolderInfo folderInfo = DAOFactory.instance(context).getFolderDao().getFolderById(fileInformation);
			if (null != folderInfo) {
				if (null != folderInfo.getName()) {
					name = folderInfo.getName();
				}
			}
		} else {
			FileFolderInfo fileInfo = DAOFactory.instance(context).getFileDao().getFile(fileInformation);
			if (null != fileInfo) {
				if (null != fileInfo.getName()) {
					name = fileInfo.getName();
				}

			}
		}

		final String names = name;

		final ClouddriveDialog rename = new ClouddriveDialog(activity, R.style.dialog_upload, R.layout.window_dialog_create_folder);
		View conventView = rename.getConventView();
		Button confirm_btn = (Button) conventView.findViewById(R.id.confirm_btn);
		Button cancle_btn = (Button) conventView.findViewById(R.id.cancle_btn);
		TextView tittleText = (TextView) conventView.findViewById(R.id.tittle_tv);
		final EditText rename_et = (EditText) conventView.findViewById(R.id.inputText_et);
		rename_et.setText(name);
		rename_et.selectAll();
		tittleText.setText(activity.getString(R.string.rename_title));

		cancle_btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				rename.dismiss();
				if (View.VISIBLE == loading_ll.getVisibility()) {
					loading_ll.setVisibility(View.GONE);
				}
			}
		});
		confirm_btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (View.GONE == loading_ll.getVisibility()) {
					loading_ll.setVisibility(View.VISIBLE);
				}
				rename.dismiss();
				final String newName = rename_et.getText().toString().trim();
				if (NameUtils.isValidFileName(newName)) {
					if (newName.equals(names)) {
						Bundle bundle = new Bundle();
						bundle.putString("folderID", fileInformation.getParent());
						Toast.makeText(activity, activity.getString(R.string.rename_filefolder_nochange), Toast.LENGTH_SHORT).show();
						if (View.VISIBLE == loading_ll.getVisibility()) {
							loading_ll.setVisibility(View.GONE);
						}
					} else {
						final SharedPreferences settings = activity.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
						new Thread(new Runnable() {
							@Override
							public void run() {
								if (fileInformation.getIsFile() == 1) {
									if (null != shareDriveService) {
										fileFolderActions.renameFile(shareDriveService, newName, fileInformation, item);
									}
								} else {
									if (null != shareDriveService) {
										fileFolderActions.renameFolder(shareDriveService, newName, fileInformation, item);
									}
								}

							}
						}).start();
					}
				} else {
					// folder name invalid
					Message msg = new Message();
					msg.what = UiConstant.FOLDER_NAME_IS_INVALID;// 24;
					handler.sendMessage(msg);
				}

			}
		});
		rename.show();
		PublicTools.showKey(rename_et, context);
	}

	/**
	 * delete file&folder
	 * 
	 * @param context
	 *            Context
	 * @param fileInformation
	 *            FileInformation
	 */
	private void delete(Context context, final FileFolderInfo fileInformation, final View item) {
		if (View.GONE == loading_ll.getVisibility()) {
			loading_ll.setVisibility(View.VISIBLE);
		}

		final AsyncTaskHandler deleteHandler = new AsyncTaskHandler() {
			@Override
			public void onExecuting() {
			}

			@Override
			public void onSuccess() {
				Message msg = new Message();
				msg.what = UiConstant.SUCCESS_ON_FILE_FOLDER_INFO_CHANGED;
				msg.arg1 = sendFromDelete;
				msg.obj = item;
				handler.sendMessage(msg);
			}

			@Override
			public void onFailure(ClientException exception) {
				if (exception.getStatusCode() == 404) {
					Message msg = handler.obtainMessage();
					msg.what = resourceIsNotExist;
					msg.arg1 = sendFromDelete;
					msg.obj = item;
					msg.sendToTarget();
				}

				// Message eMsg =
				// exceptionHandlers.obtainMessage(exception.getStatusCode(),
				// exception);
				// eMsg.sendToTarget();
			}
		};
		new Thread(new Runnable() {

			@Override
			public void run() {
				if (null != shareDriveService) {
					if (FileType.File.value() == fileInformation.getIsFile()) {// 1:file
						LogUtil.i(TAG, "start delete file..");
						fileFolderActions.deleteFile(shareDriveService, fileInformation, item);
					} else {// folder
						LogUtil.i(TAG, "start delete folder..");
						fileFolderActions.deleteFolderAsync(shareDriveService, fileInformation, deleteHandler, item);
					}
				}
			}
		}).start();
	}

	/**
	 * get file&folder list data
	 * 
	 * @param folderID
	 *            String folder id
	 */
	public void getAllFileList(int dir) {
		getAllFileList(itemIDString, dir);
	}

	private void getAllFileList(final String folderID, final int dir) {
		new Thread(new Runnable() {
			Message msg = new Message();

			List<FileFolderInfo> fileFolderList = new ArrayList<FileFolderInfo>();

			@Override
			public void run() {
				try {
					if (null != shareDriveService) {
						fileFolderList = shareDriveService.getFileFolderListFromDB(activity, ShareDriveApplication.getInstance().getWnerID(), folderID,
								PublicTools.getDes(activity), PublicTools.getOrderBy(activity), handler);
						msg.obj = fileFolderList;
						if (UiConstant.DIR_CODE_25 == dir) {
							msg.arg1 = 200;
						}
						msg.what = dir;
						LogUtil.i(TAG, "[getAllFileList]size:" + fileFolderList.size());
					}
				} catch (ClientException e) {
					msg.obj = fileFolderList;
					msg.what = UiConstant.REFRESH_FILELIST_UI_VIEW;
					LogUtil.e(TAG, "[getAllFileList]e:" + e.getStatusCode());
				}
				handler.sendMessage(msg);
			}
		}).start();
	}

	/**
	 * filfter same folder
	 * 
	 * @param folderID
	 *            String folder id
	 */
	private void isIdenticalMethod(String folderID) {
		if ("0".equals(folderID)) {
			allfile_back_mi.setVisibility(View.GONE);
		} else {
			allfile_back_mi.setVisibility(View.VISIBLE);
		}

	}

	/**
	 * show list view
	 */
	@SuppressLint("ResourceAsColor")
	private synchronized void showMsgData(List<FileFolderInfo> fileFolderList) {
		currentRsource = fileFolderList;
		allfile_scrollview.removeAllItem();
		emptyImg = null;
		if (null != fileFolderList && 0 < fileFolderList.size()) {
			BaseAdapter mAdapter = new MyFileListAdapter(activity, handler, fileFolderList, shareDriveService);
			allfile_scrollview.setAdptor(mAdapter);
			allfile_scrollview.notifyAllItem();
			Log.d("list01", "size:" + mAdapter.getCount());
		} else {
			emptyImg = new ImageView(activity);
			emptyImg.setBackgroundResource(R.mipmap.no_allfile_no_file_bg);
			allfile_scrollview.resetList();
			allfile_layout.addView(emptyImg);
		}
		if (isDraging) {
			long updateTime = DAOFactory.instance(activity).getFolderDao().getLastRefreshTime(ShareDriveApplication.getInstance().getWnerID(), itemIDString);
			if (0l == updateTime) {
				updateTime = System.currentTimeMillis();
			}
			String time = PublicTools.longToString(updateTime);
			allfile_refresh_root.setLastUpdateTime(time);
			allfile_refresh_root.finishRefresh();
			isDraging = false;
		}
		if ("0".equals(itemIDString)) {
			filelist_title_back_ll.setClickable(false);
		} else {
			if (!filelist_title_back_ll.isClickable()) {
				filelist_title_back_ll.setClickable(true);
			}
		}
		if (View.VISIBLE == loading_ll.getVisibility()) {
			loading_ll.setVisibility(View.GONE);
		}
		if (View.VISIBLE == movenews_lin.getVisibility()) {
			movenews_lin.setVisibility(View.GONE);
		}
	}

	/**
	 * search file&folder
	 * 
	 * @param limit
	 *            int
	 * @param offset
	 *            int
	 * @param name
	 *            name
	 */
	public void search(final String name) {
		if (null != name && !"".equals(name)) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					Message msg = new Message();
					try {
						List<FileFolderInfo> allFileList = null;
						if (null != shareDriveService) {
							allFileList = shareDriveService.searchInDB(ShareDriveApplication.getInstance().getWnerID(), name, activity);
							Log.d("list01", "size:" + allFileList.size());
							msg.what = UiConstant.DISPLAY_FILELIST_UI_VIEW;
							msg.obj = allFileList;
							handler.sendMessage(msg);
						}
					} catch (Exception e) {
						// Auto-generated catch block
						e.printStackTrace();
						LogUtil.e(TAG, "statueCode:" + e.toString());
					}
				}
			}).start();
		}
	}

	/**
	 * get Offset
	 * 
	 * @param a
	 *            int
	 * @param b
	 *            int
	 * @return int
	 */
	private BroadcastReceiver stateReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			int code = intent.getIntExtra("statecode", -1);
			if (0 == code) {
				LogUtil.i(TAG, "network stateReceiver:offline");
				state_re.setVisibility(View.VISIBLE);
				state_te.setText(activity.getString(R.string.allfile_offline_status));
			}
			if (1 == code) {
				LogUtil.i(TAG, "network stateReceiver:online");
				state_re.setVisibility(View.GONE);
			}

		}
	};

	private void changeFolderInfor() {
		String parentFolderId = "0";
		String lastFolderName = activity.getString(R.string.my_cloud_drive);
		String currentFolderName = "";
		if (null != DAOFactory.instance(activity).getFolderDao().getFolderById(ShareDriveApplication.getInstance().getWnerID(), itemIDString)) {
			LogUtil.e(TAG, "currentFolder is not null");
			parentFolderId = DAOFactory.instance(activity).getFolderDao().getFolderById(ShareDriveApplication.getInstance().getWnerID(), itemIDString)
					.getParent();
			currentFolderName = DAOFactory.instance(activity).getFolderDao().getFolderById(ShareDriveApplication.getInstance().getWnerID(), itemIDString)
					.getName();
			if ("0".equals(parentFolderId)) {
				lastFolderName = getString(R.string.my_cloud_drive);
			} else {
				FileFolderInfo dbFolderInfo = DAOFactory.instance(activity).getFolderDao()
						.getFolderById(ShareDriveApplication.getInstance().getWnerID(), parentFolderId);
				if (null != dbFolderInfo) {
					lastFolderName = dbFolderInfo.getName();
				}
			}
		} else {
			LogUtil.e(TAG, "currentFolder is null");
		}
		if ("0".equals(itemIDString)) {
			filelist_tittle_text.setText(lastFolderName);
			filelist_tittle_img.setVisibility(View.VISIBLE);
			current_folder_text.setText("");
		} else {
			filelist_tittle_text.setText(lastFolderName);
			filelist_tittle_img.setVisibility(View.GONE);
			current_folder_text.setText(currentFolderName);
		}
		isIdenticalMethod(itemIDString);
		// int maxMemory = (int) Runtime.getRuntime().maxMemory();
		// int totalMemory = (int) Runtime.getRuntime().totalMemory();
		// int freeMemory = (int) Runtime.getRuntime().freeMemory();
	}

	ClientExceptionRelateHandler exceptionHandlers = new ClientExceptionRelateHandler() {

		@Override
		public void handleMessage(Message msg) {
			String code = "";
			if (msg.obj instanceof ClientException) {
				ClientException exception = (ClientException) msg.obj;
				code = exception.getCode();
			}
			if (View.VISIBLE == loading_ll.getVisibility()) {
				loading_ll.setVisibility(View.GONE);
			}
			if (!filelist_title_back_ll.isClickable()) {
				filelist_title_back_ll.setClickable(true);
			}
			if (isDraging) {
				allfile_refresh_root.finishRefresh();
				isDraging = false;
			}
			setBack(true);
			onDataLoaded();
			LogUtil.e(TAG, "error stausCode:" + msg.what + " | code:" + code + " | codeDir:" + msg.arg1);
			switch (msg.what) {
			case ExceptionConstant.access_internet_Failed:
				switch (msg.arg1) {
				case ClientConfig.SENDFROMGETRESOURCE:
					break;
				}
				break;

			case ClientConfig.FILEPATH_NOT_CHANGE:
				Toast.makeText(activity, activity.getString(R.string.window_move_target_not_change), Toast.LENGTH_SHORT).show();
				break;

			// case 1000:
			// if (null != shareDriveService)
			// {
			// shareDriveService.upgradeCloudDrive(null);
			// }
			// break;

			default:
				super.handleMessage(msg);
			}
		}

		@Override
		protected void onException_401_Unauthorized(Message msg, String errorCode) {
			super.onException_401_Unauthorized(msg, errorCode);
			returnToLoginActivity();
		}

		@Override
		protected void onException_401_ClientUnauthorized(Message msg, String errorCode) {
			if (null != shareDriveService) {
				shareDriveService.clearCloudDriveCache(null);
				shareDriveService.creatMobileForbiddenDialog();
			}
			// super.onException_401_ClientUnauthorized(msg, exception);
			returnToLoginActivity();
		}

		@Override
		protected void onException_401_UnknowException(Message msg, String errorCode) {
			super.onException_401_UnknowException(msg, errorCode);
			returnToLoginActivity();
		}

		@Override
		protected void onException_403_UserLocked(Message msg, String errorCode) {
			super.onException_403_UserLocked(msg, errorCode);
			if (null != shareDriveService) {
				shareDriveService.clearCloudDriveCache(null);
			}
			returnToLoginActivity();
		}

		@Override
		protected void onException_404_NoSuchItem(Message msg, String errorCode) {
			super.onException_404_NoSuchItem(msg, errorCode);
			String folderId = "0";
			FileFolderInfo infosEntity = DAOFactory.instance(activity).getFolderDao()
					.getFolderById(ShareDriveApplication.getInstance().getWnerID(), itemIDString);
			if (null != infosEntity) {
				if (null != infosEntity.getParent()) {
					folderId = infosEntity.getParent();
				}
			}
			if (null != folderId) {
				itemIDString = folderId;
			}
			fileFolderActions.getAllFileListFromServer(ShareDriveApplication.getInstance().getWnerID(), folderId, shareDriveService, 25);
			changeFolderInfor();
		}

		@Override
		protected void onException_404_NoSuchFile(Message msg, String errorCode) {
			if (msg.obj instanceof View) {
				View viewItem = (View) msg.obj;
				MyFileListAdapter.ViewHolder viewHolder = (MyFileListAdapter.ViewHolder) viewItem.getTag();
				((MyFileListAdapter) allfile_scrollview.getAdptor()).fileList.remove(viewHolder.fileInformation);
				ServiceFactory.instance(getContext()).getLocalFileService().deleteFile(viewHolder.fileInformation);
				allfile_scrollview.removeItem(viewItem);
			}
			super.onException_404_NoSuchFile(msg, errorCode);
		}

		@Override
		protected void onException_404_NoSuchFolder(Message msg, String errorCode) {
			if (msg.obj instanceof View) {
				View viewItem = (View) msg.obj;
				MyFileListAdapter.ViewHolder viewHolder = (MyFileListAdapter.ViewHolder) viewItem.getTag();
				((MyFileListAdapter) allfile_scrollview.getAdptor()).fileList.remove(viewHolder.fileInformation);
				ServiceFactory.instance(getContext()).getLocalFileService().deleteFile(viewHolder.fileInformation);
				allfile_scrollview.removeItem(viewItem);
			} else {
				String folderId = "0";
				FileFolderInfo infosEntity = DAOFactory.instance(activity).getFolderDao()
						.getFolderById(ShareDriveApplication.getInstance().getWnerID(), itemIDString);
				if (null != infosEntity) {
					if (null != infosEntity.getParent()) {
						folderId = infosEntity.getParent();
					}
				}
				if (null != folderId) {
					itemIDString = folderId;
				}
				fileFolderActions.getAllFileListFromServer(ShareDriveApplication.getInstance().getWnerID(), folderId, shareDriveService, 25);
				changeFolderInfor();
			}
			super.onException_404_NoSuchFolder(msg, errorCode);
		}

		@Override
		public Context getContext() {
			return getActivity();
		}
	};

	private void returnToLoginActivity() {
		Intent intent = new Intent();
		intent.setClass(activity, LoginActivity.class);
		activity.startActivity(intent);
		activity.finish();
	}

	public void uplodFile(List<String> resultUrlList) {
		fileFolderActions.uploadFileOrinitLogin(shareDriveService, resultUrlList);
	}

	public void dialogAddfileClick() {
		View conventView = addFileDialog.getConventView();
		Button dialog_add_file = (Button) conventView.findViewById(R.id.dialog_add_file);

		Button dialog_add_photo = (Button) conventView.findViewById(R.id.dialog_add_photo);

		Button dialog_addfile_cancel = (Button) conventView.findViewById(R.id.dialog_addfile_cancel);

		dialog_add_file.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent dataAllFile = new Intent();
				dataAllFile.setClass(activity, FileBrowserAllFileActivity.class);
				// dataAllFile.putExtra("type", "all");
				startActivityForResult(dataAllFile, 1);
				if (null != addFileDialog) {
					addFileDialog.dismiss();
				}
			}
		});
		dialog_add_photo.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent dataPicture = new Intent();
				dataPicture.setClass(activity, FileBrowserPictureActivity.class);
				startActivityForResult(dataPicture, 1);
				if (null != addFileDialog) {
					addFileDialog.dismiss();
				}
			}
		});
		dialog_addfile_cancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (null != addFileDialog) {
					addFileDialog.dismiss();
				}
			}
		});

	}

	@Override
	public String getParent() {
		// TODO Auto-generated method stub
		return returnParent;
	}

	public void getNewsView() {
		if (View.GONE == movenews_lin.getVisibility()) {
			movenews_lin.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onDataLoaded() {
		// TODO Auto-generated method stub
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (null != activityHandler) {
					setBack(true);
					Message dissMissMsg = new Message();
					dissMissMsg.what = UiConstant.HIDE_TOP_PROGRESSBAR;
					dissMissMsg.arg1 = 1;
					activityHandler.sendMessageDelayed(dissMissMsg, 150);
				}
			}
		}).start();
	}

	public void moveConfirm() {
		new Thread(new Runnable() {

			@Override
			public void run() {

				String itemId = null;
				String oldParentId = "0";
				String moveCurrentParenId = "0";
				if (null != moveInfo) {
					itemId = moveInfo.getId();
					if (null != moveInfo.getParent()) {
						oldParentId = moveInfo.getParent();
					}
				} else {
					return;
				}
				if (null != moveParentInfo) {
					moveCurrentParenId = moveParentInfo.getId();
				}
				LogUtil.d(TAG, "{(move):[oldParentId: " + oldParentId + ",newParenId: " + moveCurrentParenId + "]}");
				if (oldParentId != null && moveCurrentParenId != null && moveCurrentParenId.equals(oldParentId)) {
					exceptionHandlers.sendEmptyMessage(ClientConfig.FILEPATH_NOT_CHANGE);
					return;
				}
				if (moveInfo.getIsFile() == 1) {
					if (null != shareDriveService) {
						fileFolderActions.removeFile(shareDriveService, moveInfo, moveParentInfo);
					}
				} else {
					if (null != shareDriveService) {
						fileFolderActions.removeFolder(shareDriveService, moveInfo, moveParentInfo);
					}
				}

			}
		}).start();
	}

	public void moveCancle() {
	}

	/**
	 * @param moveInfo
	 */
	public void startMoveActivity(FileFolderInfo moveInfo) {
		Intent intent = new Intent();
		intent.setClass(activity, AllFileMoveActivity.class);
		Bundle bundle = new Bundle();
		bundle.putSerializable("exinfo", moveInfo);
		intent.putExtra("moveItem", bundle);
		startActivityForResult(intent, 1);
		activity.overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
	}

	/**
	 * @param context
	 *            Context
	 * @param fileInformation
	 *            FileInformation
	 */
	private void setLinkInfo(Context context, final FileFolderInfo fileInformation, final View item) {
		if (View.GONE == loading_ll.getVisibility()) {
			loading_ll.setVisibility(View.VISIBLE);
		}

		new Thread(new Runnable() {
			@Override
			public void run() {
				if (null == shareDriveService) {
					return;
				}
				int shared_state = fileFolderActions.getNodeLinkedState(shareDriveService, fileInformation, item);

				if (shared_state == ClientConfig.NODE_SHARED_STATE_TRUE) {
					LogUtil.i(TAG, "start getLink..");
					fileFolderActions.getLink(shareDriveService, fileInformation, item);
				} else if (shared_state == ClientConfig.NODE_SHARED_STATE_FALSE) {
					LogUtil.i(TAG, "start createLink..");
					fileFolderActions.createLink(shareDriveService, fileInformation, item);
				} else {
					LogUtil.e(TAG, "unknown error occured when get shared state");
				}
			}
		}).start();
	}

	/**
	 * @param context
	 *            Context
	 * @param fileInformation
	 *            FileInformation
	 */
	private void shareLinkInfo(final Context context, final FileFolderInfo fileInformation, LinkInfoV2 info, final View item, final boolean isComplexAccessCode) {

		SharedPreferences settings = activity.getSharedPreferences(ClientConfig.settings, activity.MODE_APPEND);
		String address = settings.getString(ClientConfig.SERVER_ADDRESS, "");

		if (address.trim().equals("")) {
			address = ClientConfig.SERVICEADD;
		}

		StringBuffer tmp = new StringBuffer(address);
		tmp.append("/").append("p").append("/").append(info.getId());
		final String linkUrl = tmp.toString();
		final String plainAccessCode = info.getPlainAccessCode();
		Long effectiveAt = info.getEffectiveAt();
		Long expireAt = info.getExpireAt();
		final ClouddriveDialog linkDialog = new ClouddriveDialog(activity, R.style.dialog_upload, R.layout.window_dialog_link);
		View conventView = linkDialog.getConventView();
		linkDialog.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface arg0) {
				if (loading_ll != null) {
					loading_ll.setVisibility(View.GONE);
				}
			}

		});
		View copy_btn = (View) conventView.findViewById(R.id.copy_link_address);
		Button confirm_btn = (Button) conventView.findViewById(R.id.confirm_btn);
		Button cancle_btn = (Button) conventView.findViewById(R.id.cancle_btn);
		Button delete_link_btn = (Button) conventView.findViewById(R.id.delete_link_btn);
		final TextView access_modify_btn = (TextView) conventView.findViewById(R.id.access_modify_btn);
		final TextView accessControlLabel = (TextView) conventView.findViewById(R.id.control_label);
		final TextView accessCodeLabelView = (TextView) conventView.findViewById(R.id.access_code_text);
		final TextView dateLimitLabelView = (TextView) conventView.findViewById(R.id.date_limit_text);
		final EditText address_et = (EditText) conventView.findViewById(R.id.link_address);
		// final EditText code_et = (EditText)
		// conventView.findViewById(R.id.control_code);
		// final EditText beginTime = (EditText)
		// conventView.findViewById(R.id.beginValidTime);
		// final EditText endTime = (EditText)
		// conventView.findViewById(R.id.endValidTime);
		address_et.setText(linkUrl);
		address_et.setKeyListener(null);
		// code_et.setKeyListener(null);
		if (StringUtil.isBlank(plainAccessCode) && effectiveAt == null) {
			accessControlLabel.setText(activity.getString(R.string.access_limit) + activity.getString(R.string.access_public));
		}
		if (StringUtil.isNotBlank(plainAccessCode)) {
			accessCodeLabelView.setText(activity.getString(R.string.is_control) + plainAccessCode);
		} else {
			accessCodeLabelView.setText("");
		}
		if (effectiveAt != null) {
			StringBuffer tipBuffer = new StringBuffer();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			tipBuffer.append(activity.getString(R.string.link_valid_date));
			tipBuffer.append(sdf.format(new Date(effectiveAt)));
			if (expireAt != null) {
				tipBuffer.append(activity.getString(R.string.to));
				tipBuffer.append(sdf.format(new Date(expireAt)));
			} else {
				tipBuffer.append(activity.getString(R.string.to) + " " + activity.getString(R.string.forever));
			}
			dateLimitLabelView.setText(tipBuffer.toString());
		} else {
			dateLimitLabelView.setText("");
			;
		}

		final ClouddriveDialog linkControlDialog = new ClouddriveDialog(activity, R.style.dialog_upload, R.layout.window_dialog_link_control);
		View linkControlView = linkControlDialog.getConventView();
		final CheckBox codeControl = (CheckBox) linkControlView.findViewById(R.id.is_control);
		final CheckBox dateControl = (CheckBox) linkControlView.findViewById(R.id.date_control);
		final Button refresh_btn = (Button) linkControlView.findViewById(R.id.fresh_control_code);
		Button cancle_control_btn = (Button) linkControlView.findViewById(R.id.cancle_control_btn);
		Button save_control_btn = (Button) linkControlView.findViewById(R.id.save_control_btn);
		final EditText access_code_control = (EditText) linkControlView.findViewById(R.id.access_code_control);
		final EditText beginValidTime = (EditText) linkControlView.findViewById(R.id.beginValidTime);
		final EditText endValidTime = (EditText) linkControlView.findViewById(R.id.endValidTime);
		final TextView toView = (TextView) linkControlView.findViewById(R.id.date_range_label);

		if (StringUtil.isNotBlank(plainAccessCode)) {
			access_code_control.setText(plainAccessCode);
			codeControl.setChecked(true);
			access_code_control.setVisibility(View.VISIBLE);
			if (isComplexAccessCode) {
				refresh_btn.setVisibility(View.VISIBLE);
			} else {
				refresh_btn.setVisibility(View.INVISIBLE);
			}
		} else {
			codeControl.setChecked(false);
			access_code_control.setVisibility(View.INVISIBLE);
			access_code_control.setText("");
			refresh_btn.setVisibility(View.INVISIBLE);
		}
		if (isComplexAccessCode) {
			access_code_control.setFocusable(false);
			access_code_control.setFocusableInTouchMode(false);
		} else {
			access_code_control.setFocusable(true);
			access_code_control.setFocusableInTouchMode(true);
		}
		if (effectiveAt != null) {
			dateControl.setChecked(true);
			beginValidTime.setVisibility(View.VISIBLE);
			endValidTime.setVisibility(View.VISIBLE);
			toView.setVisibility(View.VISIBLE);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			beginValidTime.setText(sdf.format(new Date(effectiveAt)));
			if (expireAt != null) {
				endValidTime.setText(sdf.format(new Date(expireAt)));
			} else {
				endValidTime.setText("");
			}
		} else {
			toView.setVisibility(View.INVISIBLE);
			dateControl.setChecked(false);
			beginValidTime.setVisibility(View.INVISIBLE);
			beginValidTime.setText("");
			endValidTime.setVisibility(View.INVISIBLE);
			endValidTime.setText("");
		}
		save_control_btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (codeControl.isChecked()) {
					if (StringUtil.isBlank(access_code_control.getText().toString())) {
						Toast.makeText(activity, activity.getString(R.string.access_code_not_empty), Toast.LENGTH_SHORT).show();
						return;
					}
					if (!isComplexAccessCode && !LinkAccessCodeUtil.isValidAccessCode(access_code_control.getText().toString())) {
						Toast.makeText(activity, activity.getString(R.string.access_code_invalid), Toast.LENGTH_SHORT).show();
						return;
					}
					accessCodeLabelView.setText(activity.getString(R.string.is_control) + access_code_control.getText().toString());
				} else {
					accessCodeLabelView.setText("");
				}
				if (dateControl.isChecked()) {
					if (StringUtil.isBlank(beginValidTime.getText().toString())) {
						Toast.makeText(activity, activity.getString(R.string.access_begin_date_empty), Toast.LENGTH_SHORT).show();
						return;
					}
					try {
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
						Date beginDate = sdf.parse(beginValidTime.getText().toString());

						if (StringUtil.isNotBlank(endValidTime.getText().toString())) {
							Date endDate = sdf.parse(endValidTime.getText().toString());
							if (beginDate.getTime() > endDate.getTime()) {
								Toast.makeText(activity, activity.getString(R.string.access_date_error), Toast.LENGTH_SHORT).show();
								return;
							}
						}

					} catch (Exception e) {
						LogUtil.e("validate date rangle limit error");
						Toast.makeText(activity, activity.getString(R.string.access_date_invalid), Toast.LENGTH_SHORT).show();
						return;
					}

					StringBuffer tipBuffer = new StringBuffer();
					tipBuffer.append(activity.getString(R.string.link_valid_date));
					tipBuffer.append(beginValidTime.getText().toString());
					if (StringUtil.isNotBlank(endValidTime.getText().toString())) {
						tipBuffer.append(activity.getString(R.string.to));
						tipBuffer.append(endValidTime.getText().toString());
					} else {
						tipBuffer.append(activity.getString(R.string.to));
						tipBuffer.append(" ");
						tipBuffer.append(activity.getString(R.string.forever));
					}
					dateLimitLabelView.setText(tipBuffer.toString());
				} else {
					dateLimitLabelView.setText("");
				}
				if (!codeControl.isChecked() && !dateControl.isChecked()) {
					accessControlLabel.setText(activity.getString(R.string.access_limit) + activity.getString(R.string.access_public));
				} else {
					accessControlLabel.setText(activity.getString(R.string.access_limit));
				}
				linkControlDialog.dismiss();
				// async save
				new Thread(new Runnable() {
					@Override
					public void run() {
						LinkCreateRequestV2 linkRequest = new LinkCreateRequestV2();
						linkRequest.setPlainAccessCode(codeControl.isChecked() ? access_code_control.getText().toString() : null);
						if (dateControl.isChecked()) {
							try {
								SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
								linkRequest.setEffectiveAt(sdf.parse(beginValidTime.getText().toString()).getTime());
								if (StringUtil.isNotBlank(endValidTime.getText().toString())) {
									linkRequest.setExpireAt(sdf.parse(endValidTime.getText().toString()).getTime());
								}
							} catch (Exception e) {
								LogUtil.e("set link date limit error");
							}
						}
						new LinkAction(activity).updateLink(shareDriveService, fileInformation, linkRequest);
					}
				}).start();
			}
		});
		// set use link access code
		codeControl.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				if (!arg1) {
					access_code_control.setVisibility(View.INVISIBLE);
					refresh_btn.setVisibility(View.INVISIBLE);
				} else {
					access_code_control.setVisibility(View.VISIBLE);
					if (isComplexAccessCode) {
						access_code_control.setText(LinkAccessCodeUtil.getAccessCode(8));
						refresh_btn.setVisibility(View.VISIBLE);
					} else {
						refresh_btn.setVisibility(View.INVISIBLE);
					}
				}
			}
		});
		dateControl.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				if (!arg1) {
					beginValidTime.setVisibility(View.INVISIBLE);
					endValidTime.setVisibility(View.INVISIBLE);
					toView.setVisibility(View.INVISIBLE);
				} else {
					toView.setVisibility(View.VISIBLE);
					beginValidTime.setVisibility(View.VISIBLE);
					// beginValidTime.setText("");
					endValidTime.setVisibility(View.VISIBLE);
					// endValidTime.setText("");
				}
			}
		});
		// set link expired
		beginValidTime.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				DateTimePickerDialog dateTimePicKDialog = new DateTimePickerDialog(activity);
				dateTimePicKDialog.dateTimePicKDialog(beginValidTime, 0);
			}
		});
		endValidTime.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				DateTimePickerDialog dateTimePicKDialog = new DateTimePickerDialog(activity);
				dateTimePicKDialog.dateTimePicKDialog(endValidTime, 0);
			}
		});
		cancle_control_btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				linkControlDialog.dismiss();
			}
		});
		// re generate link code
		refresh_btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				access_code_control.setText(LinkAccessCodeUtil.getAccessCode(8));
			}
		});
		copy_btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
				cmb.setText(linkUrl);
				Toast.makeText(activity, getString(R.string.copy_success), Toast.LENGTH_SHORT).show();

			}
		});
		access_modify_btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				linkControlDialog.show();
			}
		});
		delete_link_btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				final ClouddriveDialog delete = new ClouddriveDialog(activity, R.style.dialog_upload, R.layout.dialog_linkdelete);
				View conventView = delete.getConventView();
				Button dialog_cancal = (Button) conventView.findViewById(R.id.dialog_del_link_cancel_bt);
				Button dialog_OK = (Button) conventView.findViewById(R.id.dialog_del_link_ok_bt);
				dialog_cancal.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						delete.dismiss();
					}
				});

				dialog_OK.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						linkDialog.dismiss();
						if (View.VISIBLE == loading_ll.getVisibility()) {
							loading_ll.setVisibility(View.GONE);
						}
						delete.dismiss();
						new Thread(new Runnable() {
							@Override
							public void run() {
								new LinkAction(activity).removeLinkShare(shareDriveService, exceptionHandlers, fileInformation);
							}
						}).start();
					}
				});
				delete.show();

			}
		});
		// close page
		cancle_btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				linkDialog.dismiss();
				if (View.VISIBLE == loading_ll.getVisibility()) {
					loading_ll.setVisibility(View.GONE);
				}
			}
		});
		confirm_btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (View.GONE == loading_ll.getVisibility()) {
					loading_ll.setVisibility(View.VISIBLE);
				}
				linkDialog.dismiss();

				final SharedPreferences settings = activity.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
				new Thread(new Runnable() {
					@Override
					public void run() {
						LinkCreateRequestV2 linkRequest = new LinkCreateRequestV2();
						linkRequest.setPlainAccessCode(codeControl.isChecked() ? access_code_control.getText().toString() : null);
						if (dateControl.isChecked()) {
							try {
								SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
								linkRequest.setEffectiveAt(sdf.parse(beginValidTime.getText().toString()).getTime());
								if (StringUtil.isNotBlank(endValidTime.getText().toString())) {
									linkRequest.setExpireAt(sdf.parse(endValidTime.getText().toString()).getTime());
								}
							} catch (Exception e) {
								LogUtil.e("set link date limit error");
							}
						}
						fileFolderActions.updateLink(shareDriveService, fileInformation, linkRequest, item);
					}
				}).start();
			}

		});
		linkDialog.show();

	}

	private void sendFileLinkPerson(LinkInfoV2 info, FileFolderInfo fileFolderInfo) {
		SharedPreferences settings = activity.getSharedPreferences(ClientConfig.settings, activity.MODE_APPEND);
		String address = settings.getString(ClientConfig.SERVER_ADDRESS, "");

		if (address.trim().equals("")) {
			address = ClientConfig.SERVICEADD;
		}
		StringBuffer tmp = new StringBuffer(address);
		tmp.append("/").append("p").append("/").append(info.getId());
		String linkUrl = tmp.toString();
		String plainAccessCode = info.getPlainAccessCode();
		if (StringUtil.isNotBlank(plainAccessCode)) {
			tmp.append("\r\n").append(getString((R.string.is_control))).append(plainAccessCode);
		}

		Intent sendLinkMail = new Intent(Intent.ACTION_SEND);
		sendLinkMail.setType("text/plain");
		sendLinkMail.putExtra(Intent.EXTRA_EMAIL, "");
		sendLinkMail.putExtra(Intent.EXTRA_SUBJECT, getString((R.string.share_link_title)));

		sendLinkMail.putExtra(Intent.EXTRA_TEXT, tmp.toString());
		sendLinkMail.putExtra("linkUrl", linkUrl);
		sendLinkMail.putExtra("nodeName", fileFolderInfo.getName());
		sendLinkMail.putExtra("plainAccessCode", plainAccessCode);
		startActivity(Intent.createChooser(sendLinkMail, getString(R.string.send_link_choose)));
	}

	@Override
	public int getDir() {
		// TODO Auto-generated method stub
		return this.fromDir;
	}

	@Override
	public void setDir(int dir) {
		// TODO Auto-generated method stub
		this.fromDir = dir;
	}

	public RelativeLayout getSearchView() {
		return this.search_re;
	}

	@Override
	public View getConventview() {
		// TODO Auto-generated method stub
		return viewLayoutInflater;
	}

	@Override
	public LinearLayout getShawodLayout() {
		// TODO Auto-generated method stub
		return this.shadow_ll;
	}

	public LinearLayout getLoadingView() {
		return loading_ll;
	}

	public void removeItem(View viewItem) {
		Toast.makeText(activity, R.string.allfile_filefolder_no_exist, Toast.LENGTH_SHORT).show();
		MyFileListAdapter.ViewHolder viewHolder = (MyFileListAdapter.ViewHolder) viewItem.getTag();
		((MyFileListAdapter) allfile_scrollview.getAdptor()).fileList.remove(viewHolder.fileInformation);
		ServiceFactory.instance(activity).getLocalFileService().deleteFile(viewHolder.fileInformation);
		allfile_scrollview.removeItem(viewItem);
	}

}
